<template>
  <div class="thirdCustomerManagement">
    <MetaSearchForm @on-search="tableSearch">
      <el-form ref="thirdCustomerManagement_form" :model="searchData" label-width="120px" class="thirdCustomerManagement_searchFrom">
        <el-form-item label="三方用户名称" class="thirdCustomerManagement_searchFromItem">
          <el-input v-model="searchData.clientName" placeholder="请输入三方用户名称"></el-input>
        </el-form-item>
        <el-form-item label="三方用户key" class="thirdCustomerManagement_searchFromItem">
          <el-input v-model="searchData.appKey" placeholder="请输入三方用户key"></el-input>
        </el-form-item>
        <el-form-item label="状态" class="thirdCustomerManagement_searchFromItem">
          <el-select v-model="searchData.isInactive" placeholder="请选择" clearable>
            <el-option label="启用" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="thirdCustomerManagementTable"
      class="thirdCustomerManagement_table"
      table-title="用户列表"
      :is-auto-req="true"
      :req-url="reqUrl"
      :req-data="searchDataForTable"
      req-method="post"
      :display-item="displayItem"
      :btn-group="btnGroup"
      :line-btn-group="lineBtnGroup"
      @btnClick="tableBtnClick"
      @lineBtnClick="tableInlineBtnClick"
    />
    <el-dialog
      v-if="customerDialogFlag"
      :title="itemEditData.id && itemEditData.id !== '' ? '编辑三方用户' : '新建三方用户'"
      :visible.sync="customerDialogFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="tCustomerEdit_form" :model="itemEditData" label-width="150px" :rules="editRules">
        <el-form-item label="三方用户key" prop="appKey">
          <el-input v-model="itemEditData.appKey" placeholder="请输入三方用户key" :disabled="itemEditData.id !== ''"></el-input>
        </el-form-item>
        <el-form-item label="三方用户名称" prop="clientName">
          <el-input v-model="itemEditData.clientName" placeholder="请输入三方用户名称"></el-input>
        </el-form-item>
        <el-form-item label="系统用户名称" prop="uid">
          <el-select
            v-model="itemEditData.uid"
            placeholder="请选择系统用户"
            clearable
            filterable
            style="width: 80%"
            @change="showUserName">
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="itemEditData.isInactive" active-color="#13ce66" inactive-color="#ff4949" inactive-value="1" active-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="editDialogClose()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="editDialogSubmit()"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import MetaPageTable from '../components/MetaPageTable'
import MetaSearchForm from '../components/MetaSearchForm'
import deepClone from '../utils/deepClone'
import { validateLetterNumber } from '../utils/validate'
export default {
  name: 'thirdCustomerManagement',
  components: {
    MetaPageTable,
    MetaSearchForm
  },
  data () {
    let validateKey = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入用户key'));
      } else {
        if (value.length > 80) {
          callback(new Error('用户key录入过长'));
        }
        if (!validateLetterNumber(value)) {
          callback(new Error('请输入英文或数字'));
        }
        callback();
      }
    }
    var checkName = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请输入用户名称'))
      }else{
        return callback()
      }
    }
    return {
      customerDialogFlag: false,
      reqUrl: process.env.PROGOO_GATE_WATER + 'apiCustomerInfo/getApiCustomerInfoList',
      itemEditData: {
        id: '',
        appKey: '',
        clientName: '',
        isInactive: '0',
        uid: '',
        name:''
      },
      userList: [],
      searchData: {
        clientName: '',
        appKey: '',
        isInactive: '',

      },
      searchDataForTable: {},
      editRules: {
        appKey: [
          { required: true, validator: validateKey, trigger: 'blur' }
        ],
        clientName: [
          { required: true, validator: checkName, trigger: 'blur' }
        ],
        uid: [
          { required: true, message: '请选择系统用户', trigger: 'blur' },
        ]
      },
      displayItem: [
        {
          label: '三方用户key',
          prop: 'appKey'
        },
        {
          label: '身份识别码',
          prop: 'appSecret'
        },
        {
          label: '三方用户名称',
          prop: 'clientName'
        },
        {
          label: '系统用户id',
          prop: 'uid'
        },
        {
          label: '状态',
          prop: 'isInactive',
          type: 'if',
          format: {
            '1': '停用',
            '0': '启用'
          },
          color: {
            '1': 'red',
            '0': 'green'
          }
        }
      ],
      btnGroup: [
        {
          id: 'add',
          title: '新建'
        }
      ],
      lineBtnGroup: [
        {
          id: 'edit',
          title: '编辑',
        },
        {
          id: 'delete',
          title: '删除'
        }
      ],
    }
  },
  mounted() {
    // 初始化用户列表
    this.getUserList();
  },
  methods: {
    getUserList() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/user/list",
        method: "get",
        data: {
          page: 1,
          limit: 999,
        },
      }).then((res) => {
        if (res.data.code === 200) {
          this.userList = res.data.result;
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    showUserName(e) {
      for (let i in this.userList) {
        if (e == this.userList[i].id) {
          this.searchData.name = this.userList[i].name;
        }
      }
    },
    tableBtnClick(item) {
      if (item.button === 'add') {
        this.itemEditData = {
          id: '',
          appKey: '',
          clientName: '',
          isInactive: '0'
        }
        this.customerDialogFlag = true
      }
    },
    tableInlineBtnClick(item) {
      if (item.button === 'edit') {
        this.itemEditData = deepClone(item.rows)
        this.itemEditData.isInactive = this.itemEditData.isInactive + ''
        this.customerDialogFlag = true
      }else if (item.button === 'delete') {
        this.$confirm('确认删除此用户?', '用户删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "apiCustomerInfo/delete",
            method: "post",
            data: {
              id: item.rows.id
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.$nextTick(() => {
                this.$refs.thirdCustomerManagementTable.formDataInit(true)
              })
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        })
      }
    },
    tableSearch() {
      let param = {}
      for(let key in this.searchData) {
        if(key === 'dateBetween') {
          param.datestart = this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][0] + ' 00:00:00' : ''
          param.dateend =  this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][1] + ' 23:59:59' : ''
        }else {
          param[key] = this.searchData[key]
        }
      }
      this.searchDataForTable = param
      this.$nextTick(() => {
        this.$refs.thirdCustomerManagementTable.formDataInit(true)
      })

    },
    editDialogSubmit() {
      this.$refs['tCustomerEdit_form'].validate((valid) => {
        if (valid) {
          let params = {}
          let url = process.env.PROGOO_GATE_WATER + "apiCustomerInfo/save"
          if(this.itemEditData.id !== '') {
            params.id = this.itemEditData.id
            url = process.env.PROGOO_GATE_WATER + "apiCustomerInfo/modify"
          }
          params.appKey = this.itemEditData.appKey
          params.clientName = this.itemEditData.clientName
          params.isInactive = this.itemEditData.isInactive
          params.uid = this.itemEditData.uid
          this.$fetch({
            url: url,
            method: "post",
            data: params
          }).then(res => {
            if (res.data.code === 200) {
              this.editDialogClose()
              this.$nextTick(() => {
                this.$refs.thirdCustomerManagementTable.formDataInit()
              })
            }else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              });
            }
          })
        } else {
          return false;
        }
      });
    },
    editDialogClose() {
      this.itemEditData = {
        id: '',
        appKey: '',
        clientName: '',
        isInactive: '0'
      }
      this.customerDialogFlag = false
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.thirdCustomerManagement{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .thirdCustomerManagement_table {
    width: 100%;
    overflow-y: unset;
  }
  .dataDetailsForm_item {
    line-height: normal;
    padding: 8px 0;
  }
  .thirdCustomerManagement_searchFrom {
    width: 100%;
  }
  .thirdCustomerManagement_searchFromItem {
    float: left;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
